package com.maokeyang.messageboard.config;


import com.maokeyang.messageboard.model.Message;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class InsertOrUpdateAop {

    /**
     * 指定切点
     * 匹配 com.example.demo.controller包及其子包下的所有类的所有方法
     */
    @Pointcut("execution(public * com.maokeyang.messageboard.service.impl.MessageServiceImpl.*Message(..))")
    public void serviceMethod(){
    }

    @Around("serviceMethod()")
    public Object createMessage(ProceedingJoinPoint pjp) throws Throwable{

        // 获取方法名
        //Object method = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();

        Object[] args = pjp.getArgs();
        for(Object obj : args){
            System.out.println("arguments: "+obj);
        }
        Object args0 = args[0];
        if ("addMessage".equals(methodName) || "updateMessage".equals(methodName)) {
            Message message = (Message) args0;
            if ("addMessage".equals(methodName)) {
                message.setCreatedAt(new Date());
            }
            message.setUpdatedAt(new Date());
        }
        Object retVal = pjp.proceed(args);

        return retVal;
    }
}
